//
//  WindowExtension.swift
//  SwfitBase
//
//  Created by rubick on 2023/1/13.
//

import Foundation
import UIKit

extension UIWindow {
    /** 获取keyWindow */
    static public func rk_KeyWindow() -> UIWindow? {
        var keyWindow: UIWindow?
        if #available(iOS 13.0, *) {
            // 获取info.plist多窗口配置
            let infoDict = Bundle.main.infoDictionary
            let enableScene = infoDict?.keys.contains("UIApplicationSceneManifest") != nil
            let connectedScene = UIApplication.shared.connectedScenes
            // 判断是否支持多窗口
            if enableScene && connectedScene.count > 0 {
                keyWindow = connectedScene
                    .filter { $0.activationState == .foregroundActive }
                    .compactMap { $0 as? UIWindowScene  }.first?.windows
                    .filter { $0.isKeyWindow }.first
            } else {
                keyWindow = UIApplication.shared.windows.first
                if (keyWindow?.isKeyWindow) != nil {
                    keyWindow = UIApplication.shared.keyWindow
                }
            }
        } else {
            keyWindow = UIApplication.shared.windows.first
            if (keyWindow?.isKeyWindow) != nil {
                keyWindow = UIApplication.shared.keyWindow
            }
        }
        return keyWindow
    }
}
